<?php

// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

/**
 * This block shows information about user email's
 *
 * Modified by Sergio Sama
 *
 * @package   blocks-email_list
 * @author    Toni Mas <toni.mas@uib.dot.es>
 * @copyright 2006 by <toni.mas at uib dot es>
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

require_once($CFG->dirroot .'/blocks/email_list/email/lib.php');

/**
 * Email List
 *
 * This class displays a list of emails
 *
 * @copyright 2011 Remote Learner
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class block_email_list extends block_list {

    /**
     * Initializes the class.
     *
     * @return void
     */
    function init() {
        $this->title = get_string('email_list', 'block_email_list');
    }

    /**
     * Get the refresh rate for the block
     *
     * @return int The refresh rate for the block
     * @uses $CFG
     * @uses $DB
     * @uses $USER
     */
    function get_refreshrate() {
        global $CFG, $DB, $USER;

        $emailprefs = $DB->get_record('block_email_list_preference', array('userid' => $USER->id));

        if (!$emailprefs || !isset($emailprefs->emailrefreshrate)) {
            // disable or default $CFG->block_email_list_refresh_rate;
            return isset($CFG->block_email_list_refresh_rate)
                   ? $CFG->block_email_list_refresh_rate: 0;
        }
        return $emailprefs->emailrefreshrate;
    }

    /**
     * Get the block content.
     *
     * @return string Get the block content
     * @uses $CFG
     * @uses $COURSE
     * @uses $DB
     * @uses $OUTPUT
     * @uses $USER
     */
    function get_content() {
        global $CFG, $COURSE, $DB, $OUTPUT, $USER;

        // If block have content, skip.
        if ($this->content !== null) {
            return $this->content;
        }

        // Get course id
        if (! empty($COURSE)) {
            $this->courseid = $COURSE->id;
        }

        $this->content = new stdClass;
        $this->content->items = array();
        $this->content->icons = array();

        $wwwroot = $CFG->wwwroot;

        if ($CFG->email_enable_ssl) {
            $wwwroot = str_replace('http:', 'https:', $wwwroot);
        }

        $emailicon = '<img src="'.$CFG->wwwroot.'/blocks/email_list/email/images/sobre.png"'
                    .' height="11" width="15" alt="'.get_string('course').'" />';
        $composeicon = '<img src="'. $OUTPUT->pix_url('/i/edit') .'" alt="" />';
        $spacer = $OUTPUT->spacer(array('width' => 1, 'height' => 4));

        // Only show all course in principal course, others, show it
        if ($COURSE->id == SITEID) {
            //Get the courses of the user
            $mycourses = enrol_get_my_courses();
            $this->content->footer = '<br />'.$emailicon . $spacer .'<a href="'. $CFG->wwwroot
                                   . '/blocks/email_list/email/">'
                                   . get_string('view_all', 'block_email_list').'</a>';
        } else {

            if (! empty($CFG->mymoodleredirect) && $COURSE->id == 1) {
                //Get the courses of the user
                $mycourses = enrol_get_my_courses();
                $this->content->footer = '<br />'.$emailicon. $spacer .'<a href="'. $CFG->wwwroot
                                       . '/blocks/email_list/email/">'
                                       . get_string('view_all', 'block_email_list').'</a>';
            } else {
                // Get this course
                $course = $DB->get_record('course', array('id' => $COURSE->id));
                $mycourses[] = $course;
                $this->content->footer = '<br />'.$emailicon . $spacer .'<a href="'
                                       .$CFG->wwwroot.'/blocks/email_list/email/index.php?id='
                                       .$course->id.'">'.get_string('view_inbox', 'block_email_list').'</a>';
                $this->content->footer .= '<br />'.$composeicon . $spacer .'<a href="'
                                       .$wwwroot.'/blocks/email_list/email/sendmail.php?course='
                                       .$course->id.'&amp;folderid=0&amp;filterid=0&amp;folderoldid=0'
                                       .'&amp;action=newmail">'.get_string('compose', 'block_email_list').'</a>';
            }
        }

        //Configure item and icon for this account
        $icon = '<img src="'.$CFG->wwwroot.'/blocks/email_list/email/images/openicon.gif"'
              .' height="16" width="16" alt="'.get_string('course').'" />';

        $number = 0;

        foreach ($mycourses as $mycourse) {

            ++$number; // increment for first course

            if ($number > $CFG->email_max_number_courses && !empty($CFG->email_max_number_courses)) {
                continue;
            }
            //Get the number of unread mails
            $numberunreadmails = email_count_unreaded_mails($USER->id, $mycourse->id);

            // Only show if has unreaded mails
            if ($numberunreadmails > 0) {

                $unreadmails = '<b>('.$numberunreadmails.')</b>';
                $this->content->items[] = '<a href="'.$CFG->wwwroot.'/blocks/email_list/email/index.php?id='
                                        .$mycourse->id.'">'.$mycourse->fullname .' '. $unreadmails.'</a>';
                $this->content->icons[] = $icon;
            }
        }

        if (count($this->content->items) == 0) {
            $this->content->items[] = '<div align="center">'.get_string('emptymailbox', 'block_email_list').'</div>';
        }

        return $this->content;
    }

    /**
     * Get the list of applicable formats
     *
     * @return array The list of applicable formats
     */
    function applicable_formats() {
        return array('all' => true, 'site-index' => false, 'my-index' => true, 'mod' => false, 'tag' => false);
    }

    /**
     * Indicates whether the block has configuration
     *
     * @return boolean Whether the block has configuration
     */
    function has_config() {
        return true;
    }


    /**
     * Function to be run periodically according to the moodle cron
     * This function searches for things that need to be done, such
     * as sending out mail, toggling flags etc ...
     *
     * @uses $CFG, $DB
     * @return boolean
     * @todo Finish documenting this function
     **/
    function cron() {

        global $CFG, $DB;

        mtrace('Starting email_block cron...');

        // If no isset trackbymail, return cron.
        if (!isset($CFG->email_trackbymail)) {
            return true;
        }

        // If NOT enabled
        if ($CFG->email_trackbymail == 0) {
            return true;
        }

        // Get actualtime
        $now = time();

        // Get record for mail list
        if ($block = $DB->get_record('block', array('name' => 'email_list'))) {

            if ($now > $block->lastcron) {

                // Get users who have unread mails
                $from = '{user} u,
                         {block_email_list_send} s,
                         {block_email_list_mail} m';

                $where = " WHERE u.id = s.userid
                                AND s.mailid = m.id
                                AND m.timecreated > $block->lastcron
                                AND s.readed = 0
                                AND s.sended = 1 AND u.deleted = 0";

                // If exist any users
                if ($users = $DB->get_records_sql('SELECT u.* FROM '.$from.$where)) {

                    // For each user ... get this unread mails, and send alert mail.
                    foreach ($users as $user) {

                        $mails = new stdClass();

                        // Preferences! Can send mail?
                        // Case:
                        //         1.- Site allow send trackbymail
                        //            1.1.- User doesn't define this settings -> Send mail
                        //            1.2.- User allow trackbymail -> Send mail
                        //            1.3.- User denied trackbymail -> Don't send mail

                        // User can define this preference?
                        $preferences = $DB->get_record('block_email_list_preference',
                                                       array('userid' => $user->id));
                        if ($preferences) {
                            if ($preferences->trackbymail == 0) {
                                continue;
                            }
                        }

                        $inbox = email_get_root_folder($user->id, EMAIL_INBOX); // destination folder req'd for links

                        // Get this user's unread mails
                        if ($mails = email_get_unread_mails($user->id, $block->lastcron) ) {

                            $bodyhtml = '<head>';

                            if (isset($CFG->stylesheets) && !empty($CFG->stylesheets)) {
                                foreach ($CFG->stylesheets as $stylesheet) {
                                    $bodyhtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
                                }
                            }

                            $bodyhtml .= '</head>';
                            $bodyhtml .= "\n<body id=\"email\">\n\n";

                            $bodyhtml .= '<div class="content">'.get_string('listmails', 'block_email_list')
                                       .": </div>\n\n";
                            $body = get_string('listmails', 'block_email_list')  .": \n\n";

                            $bodyhtml .= '<table border="0" cellpadding="3" cellspacing="0">';
                            $bodyhtml .= '<th class="header">'.get_string('course').'</th>';
                            $bodyhtml .= '<th class="header">'.get_string('subject', 'block_email_list').'</th>';
                            $bodyhtml .= '<th class="header">'.get_string('from', 'block_email_list').'</th>';
                            $bodyhtml .= '<th class="header">'.get_string('date', 'block_email_list').'</th>';

                            $mailsids = '';
                            if ( !empty($mails) ) {
                                $identities = array();
                                foreach ($mails as $mid) {
                                    $identities[] = $mid->mailid;
                                }
                                $mailsids = implode('a', $identities);
                            }

                            $barrier = '---------------------------------------------------------------------';

                            // Prepare messagetext
                            foreach ($mails as $mail) {

                                // Get folder
                                $folder = email_get_root_folder($mail->userid, EMAIL_SENDBOX);

                                if (! email_isfolder_type($folder, EMAIL_SENDBOX)) {
                                    continue;
                                }

                                if (isset($mail->mailid)) {
                                    $message    = $DB->get_record('block_email_list_mail',
                                                                  array('id' => $mail->mailid));
                                    $mailcourse = $DB->get_record('course',
                                                                  array('id' => $mail->course));

                                    $body .= "$barrier\n";
                                    $body .= get_string('course').": $mailcourse->fullname \n";
                                    $body .= get_string('subject', 'block_email_list').": $message->subject\n";
                                    $body .= get_string('from', 'block_email_list'). ': '
                                           .fullname(email_get_user($message->id));
                                    $body .= ' - '. userdate($message->timecreated) ."\n";
                                    $body .= "$barrier\n\n";


                                    $bodyhtml .= '<tr  class="r0">';
                                    $bodyhtml .= '<td class="cell c0">'."<a href=\"{$CFG->wwwroot}/blocks/email_list/email/index.php?id={$mail->course}&amp;folderid={$inbox->id}\">".$mailcourse->fullname.'</a></td>';
                                    $bodyhtml .= '<td class="cell c0">'."<a href=\"{$CFG->wwwroot}/blocks/email_list/email/view.php?id={$mail->mailid}&amp;course={$mail->course}&amp;action=view&amp;folderid={$inbox->id}&amp;mails={$mailsids}\">".$message->subject.'</a></td>';
                                    $bodyhtml .= '<td class="cell c0">'.fullname(email_get_user($message->id)).'</td>';
                                    $bodyhtml .= '<td class="cell c0">'.userdate($message->timecreated).'</td>';
                                    $bodyhtml .= '</tr>';
                                }
                            }

                            $bodyhtml .= '</table>';
                            $bodyhtml .= '</body>';

                            $body .= "\n\n\n\n";

                            email_to_user($user, get_string('emailalert', 'block_email_list'),
                                            get_string('emailalert', 'block_email_list') .': '
                                           .get_string('newmails', 'block_email_list'),
                                            $body, $bodyhtml);
                        }
                    }
                }
            }

            mtrace('Finishing email_block cron...');
            return true;
        } else {
            mtrace('FATAL ERROR: I couldn\'t read eMail list block');
            return false;
        }
    }

    /**
     * Tells whether the block should backup instance data
     *
     * @return boolean Whether the block should backup instance data
     */
    function backuprestore_instancedata_used() {
        return true;
    }

    /**
     * Backup emails
     *
     * @param resource $bf          The backup file resource
     * @param object   $preferences The preferences object
     * @uses $CFG
     * @return boolean
     **/
    function instance_backup($bf, $preferences) {
        global $CFG, $COURSE;

        $status = true;

        if ($preferences->backup_users == 0 or $preferences->backup_users == 1) {

            include_once("$CFG->dirroot/blocks/email_list/email/backuplib.php");

            //are there any emails to backup?
            $courseid = $COURSE->id;

            $status = email_backup_instance($bf, $preferences, $courseid);

        }
        return $status;
    }

    /**
     * Restore routine
     *
     * @param object $restore Restore object
     * @param object $data    Data object
     * @return boolean
     * @uses $CFG
     */
    function instance_restore($restore, $data) {
        global $CFG;

        $status = true;

        if ($restore->users != 0 and $restore->users != 1) {
            return $status;
        }

        include_once("$CFG->dirroot/blocks/email_list/email/restorelib.php");

        $status = email_restore_instance($data, $restore);

        return $status;
    }

    /**
     * Before delete, drop all log records
     *
     * @return void
     * @uses $DB
     */
    function before_delete() {
        global $DB;

        // Delete all email records to log_display
        if (! $DB->delete_records('log_display', array('module' => 'email_list'))) {
            print_error('faildroprecordslogdisplay', 'block_email_list');
        }
    }

    /**
     * When instance course has deleted, deleting all email_list course content.
     *
     * @return void
     * @uses $COURSE
     * @uses $DB
     */
    function instance_delete() {
        global $COURSE, $DB;

        /* When delete instance. Drop:
         *         - Folders associated at this course.
         *         - Mails of this course and all attachments.
         *         - Colaterals effects:
         *             # Drop all mail-folder references. (email_foldermail)
         *             # Drop all sendbox/inbox (email_send)
         *             # Drop all subfolders associated at this course.
         *             # Drop all filters.
         */

        global $DB;

        // Get course id
        if (! empty($COURSE)) {
            $courseid = $COURSE->id;
        } else {
            return true; // Skip
        }

        // Do not process SITEID
        if ($courseid === SITEID) {
            return true; // Skip
        }

        // Get all email references.
        if ($mailids = $DB->get_records('block_email_list_mail', array('course' => $courseid))) {

            foreach ($mailids as $mailid) {

                if (!empty($mailid->id) && ! $DB->delete_records('block_email_list_foldermail',
                                                                 array('mailid' => $mailid->id))) {
                    print_error('faildroprecordsfoldermail', 'block_email_list');
                }
            }

            // Drop all mails
            if (! $DB->delete_records('block_email_list_mail', array('course' => $courseid))) {
                print_error('faildroprecordsmail', 'block_email_list');
            }
        }

        if ($folders = $DB->get_records('block_email_list_folder', array('course' => $courseid))) {

            foreach ($folders as $folder) {
                // If user have defined who has associated folders-course, then delete all folders to this course.
                if (email_have_asociated_folders($folder->userid)) {

                    if (! email_removefolder($folder->id)) {
                        print_error('faildroprecordsfolder', 'block_email_list');
                    }
                }
            }
        }

        return true;
    }
}
